package security;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class MessageDigestUtil {
	
	//MD5  SHA/SHA-1/SHA-256/SHA-384/SHA-512  HMAC
	public static String encrptyMD5(byte[] data) throws NoSuchAlgorithmException{
		MessageDigest messageDigest = MessageDigest.getInstance("MD5");
		
		messageDigest.update(data);
		
		byte[] digest = messageDigest.digest();
		
		return byteToHexString(digest);
	}
	
	public static byte[] generaterKey() throws Exception{
		KeyGenerator key = KeyGenerator.getInstance("HmacMD5");
		SecretKey generateKey = key.generateKey();
		
		return generateKey.getEncoded();
	}
	
	public static String encrptySecretMD5(byte[] data,byte[] privateKey) throws Exception{
		SecretKey key = new SecretKeySpec(privateKey,"HmacMD5");
		
		Mac mac = Mac.getInstance("HmacMD5");
		mac.init(key);
		byte[] doFinal = mac.doFinal(data);
		
		return byteToHexString(doFinal);
	}
	
	
	public static String encrptyFileMD5(String fileName){
		
		InputStream is = null;
		DigestInputStream dis = null;
		try {
			is = new FileInputStream (fileName);
			dis = new DigestInputStream(is,MessageDigest.getInstance("MD5")); 
			
			byte[] b = new byte[1024];
			while(dis.read(b)!=-1);
				
			MessageDigest messageDigest = dis.getMessageDigest();
			byte[] digest = messageDigest.digest();
			
			return byteToHexString(digest);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally{
			if(dis !=null)
				try {
					dis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if(is!=null)
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			
		}
		
		
		
	}
	
	private static String byteToHexString(byte[] b){
		if(b!=null &&  b.length > 0){
			StringBuilder sb = new StringBuilder();	

			String temp = null;
			for(byte c : b){
				temp = Integer.toHexString(0xFF & c);
				if(temp!=null && temp.length() ==1)
					temp = "0"+temp;
			
				sb.append(temp);
			}
			return sb.toString();
		}
		return null;
	}
	
	
	public static void main(String[] args) throws Exception {
		String str = "sk";
		
		String fileName = "D:\\1.doc";
		System.out.println(encrptyMD5(str.getBytes()));
		
		System.out.println(encrptyFileMD5(fileName));
		
		System.out.println(encrptySecretMD5(str.getBytes(), generaterKey()));
	}
}
